package com.gusha.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gusha.dao.ContentComDao;
import com.gusha.model.ContentCom;
import com.gusha.model.InfoContent;
import com.gusha.model.User;

@Service
@Transactional
public class ContentComService {
	@Autowired
	private ContentComDao contentComDao;
	
	 public Page<ContentCom> findAll(Pageable pageable, ContentCom contentCom) {
	        @SuppressWarnings("serial")
	        Page<ContentCom> result = contentComDao.findAll(new Specification<ContentCom>() {
	            @Override
	            public Predicate toPredicate(Root<ContentCom> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
	                List<Predicate> list = new ArrayList<Predicate>();
	                if (contentCom.getId() != null) {
	                    list.add(cb.equal(root.get("id").as(BigInteger.class),contentCom.getId()));
	                }
	                if (contentCom.getUser() != null) {
	                    list.add(cb.equal(root.get("user").as(User.class),contentCom.getUser()));
	                }
	                if (contentCom.getContent() != null) {
	                    list.add(cb.equal(root.get("content").as(InfoContent.class),contentCom.getContent()));
	                }
	                if (contentCom.getComment() != null) {
	                    list.add(cb.equal(root.get("comment").as(String.class),contentCom.getComment()));
	                }
	                if (contentCom.getAddTime() != null) {
	                    list.add(cb.equal(root.get("addTime").as(Date.class),contentCom.getAddTime()));
	                }
	                if (contentCom.getIsDelete() != null) {
	                    list.add(cb.equal(root.get("isDelete").as(BigInteger.class),contentCom.getIsDelete()));
	                }
	                if (contentCom.getIsCheck() != null) {
	                    list.add(cb.equal(root.get("isCheck").as(BigInteger.class),contentCom.getIsCheck()));
	                }
	                
	                Predicate[] p = new Predicate[list.size()];
	                return cb.and(list.toArray(p));
	            }
	        },pageable);
	         return result;
	    }

}
